package com.hwq.sql.script.config;

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.handler.TableNameHandler;
import com.baomidou.mybatisplus.extension.plugins.inner.DynamicTableNameInnerInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;

@Configuration
public class MybatisConfig {

    /**
     * mybatis-plus 插件配置方法
     */
    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        interceptor.addInnerInterceptor(dynamicTableName());
        interceptor.addInnerInterceptor(pagination());
        return interceptor;
    }

    /**
     * 动态表名配置，这里可以根据自己的需要动态的查询不同的表
     * 场景：如，表数据量大，需要根据日期分别，如 data-20200101, date-20200102，我们就可以根据日期来判断查询那张表
     */
    private DynamicTableNameInnerInterceptor dynamicTableName() {
        DynamicTableNameInnerInterceptor dynamicTableNameInnerInterceptor = new DynamicTableNameInnerInterceptor();
        HashMap<String, TableNameHandler> map = new HashMap<String, TableNameHandler>(2) {{
            put("user", (sql, tableName) -> "t_" + tableName);
        }};
        dynamicTableNameInnerInterceptor.setTableNameHandlerMap(map);
        return dynamicTableNameInnerInterceptor;
    }

    /**
     * 分页插件，推荐最后注入，这里根据具体情况选择自己的数据库
     */
    private PaginationInnerInterceptor pagination() {
        return new PaginationInnerInterceptor(DbType.SQLITE);
    }

}
